package com.han.hotelplat.service.task.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.config.TaskManagementConfigUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.ResponseWrapTo;
import com.han.hotelplat.comm.base.EntityManage;
import com.han.hotelplat.comm.base.Pager;
import com.han.hotelplat.comm.utils.AppEmployyePushUtil;
import com.han.hotelplat.comm.utils.AreaHelp;
import com.han.hotelplat.comm.utils.DateUtil;
import com.han.hotelplat.comm.utils.ListSortUtil;
import com.han.hotelplat.comm.utils.LocationUtils;
import com.han.hotelplat.comm.utils.LogUtil;
import com.han.hotelplat.comm.utils.MD5;
import com.han.hotelplat.comm.utils.MsgHelp;
import com.han.hotelplat.comm.utils.NumberUtil;
import com.han.hotelplat.comm.utils.PushHelp;
import com.han.hotelplat.comm.utils.StrUtil;
import com.han.hotelplat.dao.childtask.ChildTaskDao;
import com.han.hotelplat.dao.emtask.EmtaskDao;
import com.han.hotelplat.dao.hotel.HotelDao;
import com.han.hotelplat.dao.task.TaskDao;
import com.han.hotelplat.dao.wallet.WalletDao;
import com.han.hotelplat.manager.LogManager;
import com.han.hotelplat.model.RoomdetailModel;
import com.han.hotelplat.model.TaskLogModel;
import com.han.hotelplat.pojo.cashextract.CashExtract;
import com.han.hotelplat.pojo.childtask.Childtask;
import com.han.hotelplat.pojo.employee.Employee;
import com.han.hotelplat.pojo.emtask.Emtask;
import com.han.hotelplat.pojo.hhm.HotelHmanager;
import com.han.hotelplat.pojo.hotel.Hotel;
import com.han.hotelplat.pojo.hotelmanager.Hotelmanager;
import com.han.hotelplat.pojo.hotelroom.HotelRoom;
import com.han.hotelplat.pojo.log.Logger;
import com.han.hotelplat.pojo.systemuser.Systemuser;
import com.han.hotelplat.pojo.task.Task;
import com.han.hotelplat.pojo.wallet.Wallet;
import com.han.hotelplat.service.childtask.ChildTaskService;
import com.han.hotelplat.service.employee.EmployeeService;
import com.han.hotelplat.service.emtask.EmTaskService;
import com.han.hotelplat.service.hhm.HotelHmanagerService;
import com.han.hotelplat.service.hotelmanager.HotelmanagerService;
import com.han.hotelplat.service.hotelroom.HotelRoomService;
import com.han.hotelplat.service.systemuser.SystemuserService;
import com.han.hotelplat.service.task.TaskService;

@Service
public class TaskServiceImpl implements  TaskService{
	@Autowired
	private WalletDao walletDao;
	@Autowired
	private TaskDao taskDao;
	@Autowired
	private HotelDao hotelDao;
	@Autowired
	private EntityManage entityManage;
	@Autowired
	private EmtaskDao emtaskDao;
	@Autowired
	private ChildTaskService childTaskService;
	@Autowired
	private HotelmanagerService hotelmanagerService;
	@Autowired
	private SystemuserService systemuserService;
	@Autowired
	private LogManager logManager;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private EmTaskService emTaskService;
	@Autowired
	private HotelHmanagerService hhmService;
	@Autowired
	private HotelRoomService hotelRoomService;
	
	@Override
	public Task getHotelTaskDteailForManager(String taskid) {
		Task task = taskDao.findTaskByTaskid(taskid);
		if(task == null){
			return null;
		}
		task.setTaskroomcount(getMinRooms(task.getHotelid()));//最低房量
		if(task.getState().intValue() == Constant.TASK_STATE_CANCER){
			task.setEmenroll(getEmcount(true, task));//已报名人数
		}else{
			task.setEmenroll(getEmcount(false, task));//已报名人数
		}
		task.setConsume(getHotelMoney(task));//累积服务费
		task.setTodayroomcount(getTodayRoomCount(task));//当日清洁房量
		task.setSumroomcount(getRooms(task));//已清洁房量
		task.setDays(getDays(task));//已清洁天数
		task.setCountdown(getCountdown(task));//任务开始倒计时
		task.setAuthAttendance(getAuthAttendance(task));//是否已确认考勤
		return task;
	}
	
	@Override
	public List<Task> getTask(Date startDate, Date endDate, Integer range,
			Integer star, List<Integer> welfare, String userlocation) {
		List<Task> returndata = new ArrayList<Task>();
		List<Task> tasklist = taskDao.getTask(startDate,endDate,star,welfare);
		double lat1 = JSONObject.parseObject(userlocation).getDoubleValue("lat");
		double lng1 = JSONObject.parseObject(userlocation).getDoubleValue("lng");
		for(Task t:tasklist){
			double lat2 = JSONObject.parseObject(t.getLocation()).getDoubleValue("lat");
			double lng2 = JSONObject.parseObject(t.getLocation()).getDoubleValue("lng");
			double relrange = LocationUtils.getDistance(lat1, lng1, lat2, lng2);
			if(range<=relrange){
				returndata.add(t);
			}
		}
		return returndata;
	}

	@Override
	public List<Task> getHotelTask(Integer hotelId, Integer state, Integer wait) {
		List<Task> list = taskDao.getHotelTask(hotelId,state,null,null, wait);
		List<Task> relist = new ArrayList<Task>();
		for(Task t : list){
			if(t.getShowapp().intValue() == Constant.APP_SHOW_CLOSE 
					&& hotelId != null && hotelId.intValue() != t.getHotelid().intValue()){//不是自己酒店的任务APP不可见任务
				continue;
			}
			t.setTaskroomcount(getMinRooms(t.getHotelid()));//最低房量
			if(t.getState().intValue() == Constant.TASK_STATE_CANCER
					|| t.getState().intValue() == Constant.TASK_STATE_STOP){
				t.setEmenroll(getEmcount(true,t));//已报名人数
			}else{
				t.setEmenroll(getEmcount(false,t));//已报名人数
			}
			t.setConsume(getHotelMoney(t));//累积服务费
			t.setTodayroomcount(getTodayRoomCount(t));//当日清洁房量
			t.setSumroomcount(getRooms(t));//已清洁房量
			t.setDays(getDays(t));//已清洁天数
			t.setCountdown(getCountdown(t));//任务开始倒计时
			t.setAuthAttendance(getAuthAttendance(t));//是否当日已确认考勤
			relist.add(t);
		}
		return relist;
	}

	private int getAuthAttendance(Task t) {
		if(getCountdown(t)>0){//任务未开始
			return 1;
		}
		if(getTodayRoomNotAuth(t)>0
				&& getTodayRoom(t) == getTodayRoomNotAuth(t)){//全部未确认
			return 2;
		}else if(getTodayRoomNotAuth(t)>0
				&& getTodayRoom(t) > getTodayRoomNotAuth(t)){//部分未确认
			return 3;
		}
		return 1;
	}

	
	private int getCountdown(Task t) {
		Date startDate = t.getStarttime();
		return DateUtil.daysDistance(new Date(),startDate);
	}

	@Override
	public Task getTaskById(Integer taskId) {
		return taskDao.findById(taskId);
	}

	@Override
	public Task saveTask(Task task) {
		if(task.getId() == null){
			taskDao.save(task);
		}else{
			taskDao.update(task);
		}
		return task;
	}

	@Override
	public Map<String, Object> publicTask(Task task,Integer userType) {
		List<HotelRoom> hotelroomLi = hotelRoomService.findHotelRoomByHotelId(task.getHotelid());
		Hotel hotel = getHotel(task.getHotelid());
		Map<String , Object> returndata = new HashMap<String, Object>();
		task.setState(Constant.TASK_STATE_CREAT);//状态为发布中
		task.setLowestroom(hotel.getTaskroomcount());//每日最低房量
		float balance = 0;
		float overdraft = 0; 
		HotelRoom hr = null;
		if(hotelroomLi.size() == 0){
			returndata.put("code", -2);
			returndata.put("message", "酒店房型未设置");
			return returndata;
		}
		
		for(HotelRoom room : hotelroomLi){
			if(room.getName().contains("标")){
				hr=room;
			}
		}
		if(hr == null){
			returndata.put("code", -2);
			returndata.put("message", "酒店房型必须设置标间");
			return returndata;
		}
		
		if(authTask(balance,overdraft, hotel,task,hr) 
				|| userType.intValue() == Constant.USER_TYPE_PLATFORM.intValue()){
			String taskid =  "T"+DateUtil.format(new Date(),"yyyyMMddHHmmss")
					+NumberUtil.getRandomNumber(100, 999);
			task.setUnitprice(hr.getHotelprice());//单价
			task.setEmunitprice(hr.getEmprice());//帮工单价
			task.setTaskid(taskid);
			task.setCreattime(new Date());
			taskDao.save(task);
			returndata.put("code", 0);
			returndata.put("balance", balance);
			returndata.put("overdraft", overdraft);
			returndata.put("message", "任务发布成功");
			return returndata;
		}
		returndata.put("code", -1);
		returndata.put("balance", balance);
		returndata.put("overdraft", overdraft);
		returndata.put("message", "账户余额不足，请充值");
		return returndata;
	}

	@Override
	public List<Task> getEmTaskList(String userid, Integer state, Integer waittask) {
		List<Task> data = taskDao.getEmTaskList(userid,state,waittask);
		List<Task> returndata  = new ArrayList<Task>();
		for(Task t : data){
			Task tmptask= getEmployeeTaskDteail(t.getTaskid(), userid);
			tmptask.setAccepttime(t.getAccepttime());
			returndata.add(tmptask);
		}
		return returndata;
	}

	// 查询报名人数(是否包含已取消的)
	public Integer getEmcount(boolean isCancelUser, Task task) {
		String sql = "";
		if(task.getStopdate() != null){//被强制取消的任务
			sql="select count(*) from tb_em_task where canceltime >= starttime and taskid='"+task.getTaskid()+"'";
		}else{
			if(!isCancelUser){
				sql="select count(*) from tb_em_task where canceltime is null and taskid='"+task.getTaskid()+"'";
			}else{
				sql="select count(*) from tb_em_task where taskid='"+task.getTaskid()+"'";
			}
		}
		return Integer.parseInt(entityManage.findBySql(sql).get(0).toString());
	}
		
	// 查询已清洁天数
	public Integer getDays(Task task) {
		//已经过去了
		int days = 0;
		if(task.getEndtime().getTime() < new Date().getTime()){
			days = DateUtil.daysDistance(task.getStarttime(),task.getEndtime())+1;
		}else{
			days = DateUtil.daysDistance(task.getStarttime(),new Date())+1;
		}
		return days<0 ? 0:days;
	}
		
	//已清洁房间数
	public Float getRooms(Task task) {
		String sql="select sum(roomcount) from tb_child_task where 1=1 "
				+ " and taskid='"+task.getTaskid()+"'";
		List re = entityManage.findBySql(sql);
		try{
			return Float.parseFloat(re.get(0)==null?"0":re.get(0).toString());
		}catch(Exception e){
			return 0f;
		}
	}
	
	//累计服务费
	public Float getEmMoney(Task task) {
		String sql="select sum(reward) from tb_child_task where result in (3,4) "
				+ " and taskid='"+task.getTaskid()+"'";
		try{
			return Float.parseFloat(entityManage.findBySql(sql).get(0).toString());
		}catch(Exception e){
			return 0.00F;
		}
	}
	
	//酒店累计消费费
	public Float getHotelMoney(Task task) {
		String sql="select sum(costmoney) from tb_child_task where result in (3,4) "
				+ " and taskid='"+task.getTaskid()+"'";
		try{
			return Float.parseFloat(entityManage.findBySql(sql).get(0).toString());
		}catch(Exception e){
			return 0.00F;
		}
	}

	/**
	 * 
	 * @description	检查该任务是否能发布，条件为该酒店钱包余额充足
	 * @author  han1088
	 * @param task 
	 * @return 
	 */
	public boolean authTask(float balance,float overdraft, Hotel hotel, Task task, HotelRoom room) {
		if(hotel.getState().intValue() != Constant.HOTEL_STATE_PASS.intValue()){
			LogUtil.info("酒店所处的状态不能发布任务酒店ID="+hotel.getId()
					+";状态="+hotel.getState());
			return false;
		}
		List<Wallet> li = walletDao.findByProperty("userid", hotel.getId().toString());
		if(li.size() == 0){//钱包没被创建
			LogUtil.info("钱包没被创建酒店ID="+hotel.getId());
			return false;
		}
		//判断酒店钱包是否被激活
		Wallet wallet = li.get(0);
		if(wallet.getState().intValue() != Constant.WALLET_STATE_ACTIVE){//钱包未激活
			LogUtil.info("钱包没被激活酒店ID="+hotel.getId());
			return false;
		}
		
		List<Task> tli = getHotelTask(hotel.getId(),null,1);//查询待处理的订单
		balance = li.get(0).getBalance();
		overdraft = li.get(0).getOverdraft();//获取钱包余额
		float totalCost = 0;
		for(Task t : tli){
			int days = DateUtil.daysDistance(t.getStarttime(), t.getEndtime());
			//服务中的订单需要从当前时间判断所需时间
			if(t.getState().intValue() == Constant.TASK_STATE_INSERVICE){
				days = DateUtil.daysDistance(new Date(), t.getEndtime());
			}
			float expectedCost = hotel.getTaskroomcount()*room.getHotelprice()
					*t.getUsercount()*(days+1);//预计花费(最低房量*单价*帮工人数*天数)
			totalCost = totalCost+expectedCost;
		}
		
		if(totalCost >= (balance+overdraft)){
			LogUtil.info("累积发布的任务已经超过了酒店钱包余额，酒店ID="+hotel.getId());
			return false;
		}
		
		//当前任务是否超过钱包余额
		int days = DateUtil.daysDistance(task.getStarttime(), task.getEndtime());
		if(hotel.getTaskroomcount() == null ){
			LogUtil.info("酒店资料未填入最低房量或者单价"+hotel.getId());
			return false;
		}
		float expectedCost = hotel.getTaskroomcount() * room.getHotelprice()
				* task.getUsercount() * (days+1);//预计花费(最低房量*单价*帮工人数*天数)
		if((balance+overdraft)<expectedCost){
			LogUtil.info("钱包余额不足;酒店ID="+hotel.getId()
					+",余额："+balance+";预计花费："+expectedCost);
			return false;
		}
		return true;
	}

	/**
	 * 
		 * @description	获取最低房量
		 * @author  han1088
		 * @return
	 */
	public float getMinRooms(Integer hotelid){
		Hotel h = getHotel(hotelid);
		if(h==null){
			return 0;
		}
		Float count = getHotel(hotelid).getTaskroomcount();
		if(count == null){
			return 0;
		}
		return getHotel(hotelid).getTaskroomcount();
	}
	
	/**
	 * 
		 * @description	获取单价
		 * @author  han1088
		 * @return
	 */
	public float getUnitprice(Integer hotelid){
		return getHotel(hotelid).getUnitprice();
	}
	
	/**
	 * 
		 * @description	获取酒店相关信息
		 * @author  han1088
		 * @return
	 */
	private Hotel getHotel(Integer hotelid) {
		return hotelDao.findById(hotelid);
	}
	
	/**
	 * 
		 * @description	获取当日清洁房量
		 * @author  han1088
		 * @return
	 */
	public float getTodayRoomCount(Task task){
		String sql="select sum(roomcount) from tb_child_task where"
				+ " taskid='"+task.getTaskid()+"'"
				+ " and creattime = '" + DateUtil.formatYMD(new Date())+"'";
		try{
			return Float.parseFloat(entityManage.findBySql(sql).get(0).toString());
		}catch(Exception e){
			return 0;
		}
	}

	/**
	 * 
		 * @description	获取当日未确认的清洁房量
		 * @author  han1088
		 * @return
	 */
	public int getTodayRoomNotAuth(Task task){
		String sql="select count(*) from tb_child_task where result in (1,2)"
				+ " and taskid='"+task.getTaskid()+"'"
				+ " and creattime = '" + DateUtil.formatYMD(new Date())+"'";
		try{
			return Integer.parseInt(entityManage.findBySql(sql).get(0).toString());
		}catch(Exception e){
			return 0;
		}
	}
	
	/**
	 * 
		 * @description	获取当日未确认的清洁房量
		 * @author  han1088
		 * @return
	 */
	public int getTodayRoom(Task task){
		String sql="select count(*) from tb_child_task where"
				+ " taskid='"+task.getTaskid()+"'"
				+ " and creattime = '" + DateUtil.formatYMD(new Date())+"'";
		try{
			return Integer.parseInt(entityManage.findBySql(sql).get(0).toString());
		}catch(Exception e){
			return 0;
		}
	}
	
	/**
	 * 
		 * @description	获取当日未确认的清洁房量
		 * @author  han1088
		 * @return
	 */
	public int getTodayEmRoomNotAuth(String emid, Task task){
		String sql="select count(*) from tb_child_task where result= 0"
				+ " and taskid='"+task.getTaskid()+"'"
				+ " and creattime = '" + DateUtil.formatYMD(new Date())+"'"
				+ " and emid='"+emid+"'";
		try{
			return Integer.parseInt(entityManage.findBySql(sql).get(0).toString());
		}catch(Exception e){
			return 0;
		}
	}
	
	@Override
	public Task getHotelTaskDteail(String taskid) {
		Task task = taskDao.findTaskByTaskid(taskid);
		if(task == null){
			return null;
		}
		task.setTaskroomcount(getMinRooms(task.getHotelid()));//最低房量
		if(task.getState().intValue() == Constant.TASK_STATE_CANCER
				|| task.getState().intValue() == Constant.TASK_STATE_STOP.intValue()){
			task.setEmenroll(getEmcount(true, task));//已报名人数
		}else{
			task.setEmenroll(getEmcount(false, task));//已报名人数
		}
		task.setConsume(getHotelMoney(task));//累积服务费
		task.setEmconsume(getEmMoney(task));//累积服务费
		task.setTodayroomcount(getTodayRoomCount(task));//当日清洁房量
		task.setSumroomcount(getRooms(task));//已清洁房量
		task.setDays(getDays(task));//已清洁天数
		task.setCountdown(getCountdown(task));//任务开始倒计时
		task.setAuthAttendance(getAuthAttendance(task));//是否已确认考勤
		if(task.getState().intValue() == Constant.TASK_STATE_CANCER.intValue()){//服务取消
			String canceruser = task.getCanceruser();
			if(canceruser != null){
				task.setIsCancelOfHepler(Integer.parseInt(canceruser.split("=")[0]));
			}else{
				//酒店取消
				task.setIsCancelOfHepler(2);
			}
			task.setIsJoin(3);//任务已取消
		}
		return task;
	}

	@Override
	public Map<String, Object> cancerTaskByHotel(String taskid, String cancercause, String canceruser) {
		Map<String , Object> returndata = new HashMap<String, Object>();
		Task task = taskDao.findTaskByTaskid(taskid);
		int state = task.getState();
		if(state >= Constant.TASK_STATE_INSERVICE.intValue()){
			returndata.put("code", -1);
			returndata.put("message", "已服务状态中不能取消");
			return returndata;
		}
		task.setState(Constant.TASK_STATE_CANCER);
		task.setCancercause(cancercause);//取消原因
		task.setStopdate(new Date());
		task.setCanceruser(canceruser);
		taskDao.update(task);
		//向帮工任务添加取消时间
		String sql="update tb_em_task set canceltime='"
		+ DateUtil.formatYMDHMS(new Date())+"' "
		+" where taskid='"+task.getTaskid()+"'";
		emtaskDao.updateBySQL(sql);
		List<Emtask> data = emTaskService.getEmTaskByTakid(taskid);
		for(Emtask emt : data){
			try {
				//发送短信通知帮工
				MsgHelp.sendHotelCancerTask(emt.getTel(), emt.getRealname(), taskid);
			} catch (ClientException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(!StrUtil.isNullOrEmpty(emt.getPushkey())){
				JSONObject reqparam = new JSONObject();
				reqparam.put("taskId", taskid);
				AppEmployyePushUtil.pushMessage(emt.getPushkey(), 
						"【有人有活】", "您的任务"+taskid+"已被酒店取消，点击查看详情", "pageOrderDetail", reqparam);
			}
			
		}
		returndata.put("code", 0);
		returndata.put("message", "取消成功");
		return returndata;
	}

	@Override
	public void updateTask(Task t) {
		taskDao.update(t);			
	}

	@Override
	public List<Task> getHotelTask(Integer hotelId, Integer state,
			Date startTime, Date endTime) {
		return taskDao.getHotelTask(hotelId,state,startTime,endTime,null);
	}

	@Override
	public Map<String, Object> cancerEmTaskByManager(String emid, String taskid,
			String cancercause, Integer constraint) {
		Map<String , Object> returndata = new HashMap<String, Object>();
		Task task = taskDao.findTaskByTaskid(taskid);
		if(constraint == null || constraint.intValue() != 1){//未点击强制取消
			//TODO 查看是否还有未确认的考勤
			Emtask et = emTaskService.getEmTask(taskid, emid);
			if(et.getIsstop() == null || et.getIsstop().intValue() != 1){//未中途停止
				Map<String, Object> re = childTaskService.getEmTaskAttendance(taskid, emid,null);
				List<Childtask> li = (List<Childtask>) re.get("childtaskList");
				for(Childtask ct : li){
					if(ct.getResult().intValue() ==  Constant.ATTENDANCE_NO_SUBMIMT
							|| ct.getResult().intValue() ==  Constant.ATTENDANCE_SUBMIMT){
						returndata.put("code", -2);
						returndata.put("message", "该帮工存在未确认的考勤，如果强制终止，未确认考勤金额将不转账到帮工账户，是否强制终止？");
						return returndata;
					}
				}
			}
		}
		
		//如果订单处于待服务状态则修改为发布中
		if(task.getState().intValue() == Constant.TASK_STATE_WAITSERVICE.intValue()){
			task.setState(Constant.TASK_STATE_CREAT);
			task.setCancercause(cancercause);
			taskDao.update(task);
		}
		
		//如果订单处于服务中取消帮工
		if(task.getState().intValue() == Constant.TASK_STATE_INSERVICE.intValue()){
			String sql="update tb_em_task set isstop=1 where taskid='"+task.getTaskid()+"' and emid="+emid;
					emtaskDao.updateBySQL(sql);
					
			//待确认的考勤要设置为已失效
			sql="update tb_child_task set result=5 where taskid='"+task.getTaskid()
					+"' and emid="+emid + " and result in(1,2)";
					entityManage.updateBySql(sql);
			returndata.put("code", 1);//区别为强制取消
			returndata.put("message", "取消成功");
			return returndata;
		}
		
		String sql="update tb_em_task set canceltime='"
				+ DateUtil.formatYMDHMS(new Date())+"',"
				+ " cancercause='"+cancercause+"'"
				+ " where taskid='"+task.getTaskid()+"' and emid="+emid;
				emtaskDao.updateBySQL(sql);
		returndata.put("code", 0);
		returndata.put("message", "取消成功");
		return returndata;
	}

	@Override
	public Task getEmployeeTaskDteail(String taskid, String userid) {
		Task task = taskDao.findTaskByTaskid(taskid);
		if(task == null){
			return null;
		}
		task.setTaskroomcount(getMinRooms(task.getHotelid()));//最低房量
		if(task.getState().intValue() == Constant.TASK_STATE_CANCER.intValue()
				|| task.getState().intValue() == Constant.TASK_STATE_STOP.intValue()){
			task.setEmenroll(getEmcount(true,task));//已报名人数
		}else{
			task.setEmenroll(getEmcount(false,task));//已报名人数
		}
		task.setDays(getDays(task));//已清洁天数
		task.setCountdown(getCountdown(task));//任务开始倒计时
		task.setUnitprice(task.getEmunitprice());
		Emtask emtask = emtaskDao.getEmTask(taskid, userid);
		
		if(emtask == null){//未报名
			task.setIsJoin(2);//是否已报名1已报名，2未报名,3已取消
			task.setJointime(null);//报名时间
			task.setTodayroomcount(getEmTodayRoomCount(userid,task));//今日清洁数量
			task.setSumroomcount(getEmRooms(userid,task));//已清洁房量
			task.setConsume(getEmMoney(userid,task));//累积服务费
			task.setIsUpWord(1);//未提交考勤
			task.setIsConfirmWork(1);//未确认考勤
			return task;
		}
		if(emtask != null && task.getStarttime().getTime() < emtask.getCreattime().getTime()){//任务开始后才报名的
			task.setStarttime(emtask.getCreattime());
		}else{
			task.setStarttime(task.getStarttime());
		}
		task.setIsJoin(1);
		if(task.getState().intValue() == Constant.TASK_STATE_CANCER.intValue()){//服务取消
			String canceruser = task.getCanceruser();
			if(canceruser != null){
				task.setIsCancelOfHepler(Integer.parseInt(canceruser.split("=")[0]));
			}else{
				//酒店取消
				task.setIsCancelOfHepler(2);
			}
			task.setIsJoin(3);//任务已取消
		}else if(task.getState().intValue() == Constant.TASK_STATE_STOP.intValue() 
				&& (emtask.getIsstop() ==null 
				|| emtask.getIsstop() .intValue() == 0)){//后台强制停止(排除服务过程中停止服务的帮工)
			if(emtask.getCanceltime() != null){
				//平台取消
				task.setIsCancelOfHepler(3);
				task.setIsJoin(4);//任务已取消
				task.setCancercause(emtask.getCancercause());
			}else{
				//平台取消
				task.setIsCancelOfHepler(3);
				task.setIsJoin(4);//任务已取消
			}
		}else if(emtask.getCanceltime() != null 
				&& task.getState().intValue() != Constant.TASK_STATE_CANCER.intValue()){//服务开始前取消的
			//帮工取消
			task.setIsCancelOfHepler(1);
			task.setIsJoin(3);//任务已取消
			task.setCancercause(emtask.getCancercause());
		}else if(emtask.getIsstop() !=null 
				&& emtask.getIsstop() .intValue() == 1){
			//帮工取消
			task.setIsCancelOfHepler(3);
			task.setIsJoin(4);//任务已取消
			task.setCancercause(emtask.getCancercause());
			task.setState( Constant.TASK_STATE_STOP);
		}
		task.setTodayroomcount(getEmTodayRoomCount(userid,task));//今日清洁数量
		task.setSumroomcount(getEmRooms(userid,task));//已清洁房量
		task.setConsume(getEmMoney(userid,task));//累积服务费
		task.setJointime(emtask.getCreattime());//报名时间
		int re = getAuthEmAttendance(userid, task);
		if(re == Constant.ATTENDANCE_NO_SUBMIMT){
			task.setIsUpWord(2);//未提交考勤
			task.setIsConfirmWork(2);//未确认考勤
		}
		if(re == Constant.ATTENDANCE_SUBMIMT){
			task.setIsUpWord(1);//已提交考勤
			task.setIsConfirmWork(2);//未确认考勤
		}
		if(re == Constant.ATTENDANCE_HASAUTH){
			task.setIsUpWord(1);//已提交考勤
			task.setIsConfirmWork(1);//未确认考勤
		}
		if(re == Constant.ATTENDANCE_END){
			task.setIsUpWord(1);//已提交考勤
			task.setIsConfirmWork(1);//已确认考勤
		}
		task.setNowdatetime(new Date());
		return task;
	}

	//获取当天考勤状态，一天就一条数据
	public int getAuthEmAttendance(String userid,Task task) {
		String hql = "from Childtask where taskid='"+task.getTaskid()+"'"
				+ " and creattime = '" + DateUtil.formatYMD(new Date())+"'"
				+ " and emid='"+userid+"'";
		List<Childtask> re = entityManage.findByHql(hql);
		for(Childtask ct : re){
			return ct.getResult();
		}
		return 1;
	}

	private int getEmMoneyDays(String userid, Task task) {
		String sql="select count(*)from tb_child_task where"
				+ " taskid='"+task.getTaskid()+"'"
				+ " and emid='"+userid+"'";
		try{
			return Integer.parseInt(entityManage.findBySql(sql).get(0).toString());
		}catch(Exception e){
			return 0;
		}
	}

	private float getEmMoney(String emid, Task task) {
		String sql="select sum(reward) from tb_child_task where result in (3,4) "
				+ " and taskid='"+task.getTaskid()+"'"
				+ " and emid='"+emid+"'";
		try{
			return Float.parseFloat(entityManage.findBySql(sql).get(0).toString());
		}catch(Exception e){
			return 0.00F;
		}
	}
	
	private float getEmTodayRoomCount(String emid, Task task) {
		String sql="select sum(roomcount) from tb_child_task where"
				+ " taskid='"+task.getTaskid()+"'"
				+ " and creattime = '" + DateUtil.formatYMD(new Date())+"'"
				+ " and emid='"+emid+"'";
		try{
			return Float.parseFloat(entityManage.findBySql(sql).get(0).toString());
		}catch(Exception e){
			return 0;
		}
	}
	
	private Float getEmRooms(String userid, Task task) {
		String sql="select sum(roomcount) from tb_child_task where result in (1,2,3,4) "
				+ " and taskid='"+task.getTaskid()+"'"
				+ " and emid='"+userid+"'";
		List re = entityManage.findBySql(sql);
		try{
			return Float.parseFloat(re.get(0)==null?"0":re.get(0).toString());
		}catch(Exception e){
			return 0f;
		}
	}

	@Override
	public Map<String, Object> cancerEmTaskByEm(String emid, String taskid,
			String cancercause) {
		Map<String , Object> returndata = new HashMap<String, Object>();
		Task task = taskDao.findTaskByTaskid(taskid);
		if(task.getState().intValue() != Constant.TASK_STATE_CREAT.intValue()
				&& task.getState().intValue() != Constant.TASK_STATE_WAITSERVICE.intValue()){//任务一开始不能取消
			returndata.put("code", -1);
			returndata.put("message", "该状态下的任务不能取消");
			return returndata;
		}
		//如果订单处于待服务状态则修改为发布中
		if(task.getState().intValue() == Constant.TASK_STATE_WAITSERVICE.intValue()){
			task.setState(Constant.TASK_STATE_CREAT);
			taskDao.update(task);
		}
		
		String sql="update tb_em_task set canceltime='"
		+ DateUtil.formatYMDHMS(new Date())+"',"
		+ " cancercause='"+cancercause+"'"
		+ " where taskid='"+task.getTaskid()+"' and emid='"+emid+"'";
		emtaskDao.updateBySQL(sql);
		Employee em = employeeService.getEmployee(emid);
		returndata.put("code", 0);
		returndata.put("message", "取消成功");
		
		HotelHmanager hhm = null;
		Hotelmanager hm = null;
		if(task.getPublisher() != null){
			List<HotelHmanager> hmli= hhmService.getBindHotelManager(task.getHotelid(), task.getPublisher(), 1);
			if(hmli.size() == 1){
				hhm = hmli.get(0);
			}else{
				hmli= hhmService.getBindHotelManager(task.getHotelid(), null, 1);
				if(hmli.size() > 0){
					hhm = hmli.get(0);
				}
			}
			if(hhm == null){//没有管家
				return returndata;
			}
			hm = hotelmanagerService.findByUserid(hhm.getHmuserid());
			if(hm != null){
				//发送短信通知酒店
				try {
					MsgHelp.sendEmExitTask(hm.getTel(), hm.getRealname(), em.getRealname(), task.getTaskid());
				} catch (ClientException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return returndata;
	}

	@Override
	public Pager<Task> findHotelTaskByPage(String startDate, String endDate,
			Integer state, Integer areaCode, String condition,
			Integer pageNo, String emInfo) {
		Pager<Task> data = new Pager<Task>(20, 0, 0, 0, new ArrayList<Task>());
		StringBuffer sbf = new StringBuffer( " from  tb_hotel as h, tb_task as t ");
				
				
		StringBuffer  where = new StringBuffer( " where t.hotelid=h.id  " );
		if(StringUtils.isNotBlank(condition)){
			sbf.append("left join tb_hotel_hmanager as hhm  on hhm.hmuserid=t.publisher and  hhm.hotelid=t.hotelid ");
			where.append(" and (t.tel like '%"+condition+"%'"
					+ " or t.taskid like '%"+condition +"%'"
					+ " or h.hotelname like '%"+condition+"%'"
					+ " or t.realname like '%"+condition+"%' "
					+ " or hhm.hmname like '%"+condition+"%' "
					+ " or hhm.hmtel like '%"+condition+"%' "
				    + ")");
		}
		if(startDate != null && !startDate.isEmpty()){
			where.append(" and t.starttime >= '"+startDate+" 00:00:00'");
		}
		if(endDate != null && !endDate.isEmpty()){
			where.append(" and t.starttime <= '"+endDate+" 23:59:59'");
		}
		if(state != null  && state.intValue() != 0){
			where.append(" and t.state ="+state);
		}
		if(StringUtils.isNotBlank(emInfo)){
			String sql = "select et.taskid from tb_employee as em, tb_em_task as et where em.userid = et.emid and (em.realname like '%"+emInfo+"%'"
					+ " or em.tel like '%"+emInfo+"%')";
			
			entityManage.findBySql(sql);
			List<String> li = entityManage.findBySql(sql);
			StringBuffer sb = new StringBuffer(" and t.taskid in(");
			if(li.size() == 0){
				return data;
			}
			for(int i=0; i<li.size(); i++){
				String emid = li.get(i);
				if(i == (li.size()-1)){
					sb.append("'"+emid +"')");
				}else{
					sb.append("'"+emid+"',");
				}
			}
			where.append(sb.toString());
		}
		
		if(areaCode != null && areaCode.intValue()>100000){//区域码至少6位
			String w_areaCode = areaCode.toString();
			int x=0;
			String w_area="";
			if(w_areaCode.endsWith("0000")) {
				//精度 省份
				x=9999;
			}else if(w_areaCode.endsWith("00")) {
				//精度 市
				x=99;
			}else {
				//精度 区
				x=0;
			}
			//要的   - 条件  >=0
			//410610-410000 <= 9999
			//410610-410600 <= 99
			//410610-410610 == 0
			w_area=" and convert(h.area,signed) - "+areaCode +" >=0 ";
			w_area+=" and convert(h.area,signed) - "+areaCode +" <= "+x;
			where.append(w_area);
		}
		
		where.append(" order by t.creattime desc");
		StringBuffer fromSql = new StringBuffer(sbf.toString() + where.toString());
		
		sbf.insert(0, "select t.id,t.taskid,h.hotelname,t.tel,h.area,t.starttime,"
				+ "t.endtime,t.unitprice,t.emunitprice,t.state,t.usercount, t.publisher, "
				+ "t.creattime, t.stopdate,t.realname ");
		sbf.append(where.toString());
		short pageSize = 20;
		data = entityManage.findBySqlPage(sbf.toString(), fromSql.toString(),  pageNo, pageSize);
		List<Task> taskli = new ArrayList<Task>();
		List li = data.getList();
		for(int i= 0 ; i<li.size(); i++){
			Object[] ory = (Object[]) li.get(i);
			Task t = new Task();
			if(ory[0] != null){//ID
				t.setId(Integer.parseInt(ory[0].toString()));
			}
			if(ory[1] != null){//任务号
				t.setTaskid(ory[1].toString());
			}
			if(ory[2] != null){//酒店名称
				t.setHotelname(ory[2].toString());
			}
			if(ory[3] != null){//电话
				t.setTel(ory[3].toString());
			}
			if(ory[4] != null){//绑定的酒店数量
				t.setArea(Integer.parseInt(ory[4].toString()));
			}
			if(ory[5] != null){//开始时间
				t.setStarttime(DateUtil.parseYMD(ory[5].toString()));
			}
			if(ory[6] != null){//结束时间
				t.setEndtime(DateUtil.parseYMD(ory[6].toString()));
			}
			if(ory[7] != null){//酒店单价
				t.setUnitprice(Float.valueOf(ory[7].toString()));
			}
			if(ory[8] != null){//帮工单价
				t.setEmunitprice(Float.valueOf(ory[8].toString()));
			}
			if(ory[9] != null){//状态
				t.setState(Integer.valueOf(ory[9].toString()));
			}
			if(ory[10] != null){//帮工数量
				t.setUsercount(Integer.valueOf(ory[10].toString()));
			}
			if(ory[11] != null){//发布者
				t.setPublisher(ory[11].toString());
			}
			if(ory[12] != null){//创建时间
				t.setCreattime(DateUtil.parseYMDHMS(ory[12].toString()));
			}
			if(ory[13] != null){//终止时间
				t.setStopdate(DateUtil.parseYMD(ory[13].toString()));
			}
			if(ory[14] != null){//发布者姓名
				t.setRealname(ory[14].toString());
			}
			taskli.add(t);
		}
		data.setList(taskli);
		for(Task t : data.getList()){
			String tel = "";
			String realname = "";
			if(StringUtils.isNotBlank(t.getTel())){
				tel=t.getTel();
				realname = t.getRealname();
			}else{
				Hotelmanager hm = hotelmanagerService.findByUserid(t.getPublisher());
				if(hm == null){//可能是后台人员发布的订单
					Systemuser user = systemuserService.findUserByUserid(t.getPublisher());
					if(user != null){
						tel=user.getTel();
						realname = user.getRealname();
					}else{
						System.out.println(t.getPublisher());
					}
				}else{
					tel=hm.getTel();
					realname = hm.getRealname();
				}
			}
			t.setDays(DateUtil.daysDistance(t.getStarttime(), t.getEndtime())+1);
			t.setEmenroll(getEmcount(false,t));
			t.setTel(tel);
			t.setRealname(realname);
			if(t.getArea() != null){
				t.setAreaModel(AreaHelp.getInstance().getAreaModels(t.getArea().toString()));
			}
		}
		return data;
	}

	@Override
	public void update(Task t) {
		taskDao.update(t);
	}

	@Override
	public Map<String, Object> stopTaskByHotel(String taskid,
			String cancercause, Integer constraint, String realname) {
		Map<String , Object> returndata = new HashMap<String, Object>();
		Task oldtask = taskDao.findTaskByTaskid(taskid);
		int state = oldtask.getState();
		Task task = taskDao.findTaskByTaskid(taskid);
		task.setState(Constant.TASK_STATE_STOP);//设置为已停止
		task.setCancercause(cancercause);//结束原因
		task.setStopdate(new Date());
		taskDao.update(task);
		
		//处于服务中或者已服务的需要转钱到帮工钱包
		if(state == Constant.TASK_STATE_INSERVICE.intValue()
				|| state == Constant.TASK_STATE_HASSERVICE.intValue()){
			returndata = childTaskService.paymentChildTaskToEm(task.getTaskid(), 
					task.getHotelid(), task.getPublisher(),constraint,realname);
			int code = (int) returndata.get("code");
			if(code != 0){
				//没有付款成功退回上一个状态
				taskDao.update(oldtask);
				return returndata;
			}
		}
		
		//向帮工任务添加取消时间
		String sql="update tb_em_task set canceltime='"
		+ DateUtil.formatYMDHMS(new Date())+"' "
		+ " where taskid='"+task.getTaskid()+"'";
		emtaskDao.updateBySQL(sql);
		if(returndata.size() == 0){
			returndata.put("code", 0);
			returndata.put("message", "任务终止成功");
		}
		return returndata;
	}

	@Override
	public List<Task> exportHotelTask(String startDate, String endDate,
			Integer state, Integer areaCode, String condition) {
		StringBuffer sbf = new StringBuffer( " from Task as t, Hotel as h where t.hotelid=h.id" );
		if(startDate != null && !startDate.isEmpty()){
			sbf.append(" and t.starttime >= '"+startDate+" 00:00:00'");
		}
		if(endDate != null && !endDate.isEmpty()){
			sbf.append(" and t.starttime <= '"+endDate+" 23:59:59'");
		}
		if(state != null  && state.intValue() != 0){
			sbf.append(" and t.state ="+state);
		}
		if(StringUtils.isNotBlank(condition)){
			sbf.append(" and (t.tel like '%"+condition+"%'"
					+ " or t.taskid like '%"+condition +"%'"
					+ " or t.realname like '%"+condition+"%')");
		}
		
		if(areaCode != null && areaCode.intValue()>100000){//区域码至少6位
			String w_areaCode = areaCode.toString();
			int x=0;
			String w_area="";
			if(w_areaCode.endsWith("0000")) {
				//精度 省份
				x=9999;
			}else if(w_areaCode.endsWith("00")) {
				//精度 市
				x=99;
			}else {
				//精度 区
				x=0;
			}
			//要的   - 条件  >=0
			//410610-410000 <= 9999
			//410610-410600 <= 99
			//410610-410610 == 0
			w_area=" and convert(h.area,signed) - "+areaCode +" >=0 ";
			w_area+=" and convert(h.area,signed) - "+areaCode +" <= "+x;
			sbf.append(w_area);
		}
		
		sbf.append(" order by t.creattime desc");
		
		sbf.insert(0, "select new Task(t.id,t.taskid,h.hotelname,t.tel,h.area,t.starttime,"
				+ "t.endtime,t.unitprice,t.emunitprice,t.state,t.usercount, t.publisher,t.creattime,t.hotelid)");
		List<Task> li = taskDao.findByHQL(sbf.toString());
		for(Task t:li){
			t.setDays(getDays(t));
			t.setEmenroll(getEmcount(false, t));
			t.setSumroomcount(getRooms(t));
			t.setConsume(getHotelMoney(t));//酒店总支出
			t.setEmEeward(getEmMoney(t));//帮工收入
			setRoomprice(t);
			List<Emtask> emtli = emtaskDao.getEmTaskByTaskid(t.getTaskid());
			Map<String , List<Emtask>> emtmap = new HashMap<String, List<Emtask>>();
			emtmap.put(t.getTaskid(), emtli);
			for(Emtask et : emtli){
				Map<String, Object>ctLiMap = childTaskService.getEmTaskAttendance(et.getTaskid(),
						et.getEmid(), null);
				List<Childtask>cli = (List<Childtask>) ctLiMap.get("childtaskList");
				et.setSumroomcount((float)ctLiMap.get("sumroomcount"));
				et.setReward(et.getSumroomcount()*t.getEmunitprice());
				
				Map<String, Float> ctMap = new  HashMap<String, Float>();
				for(Childtask ct : cli){
					ctMap.put(DateUtil.formatYMD(ct.getCreattime()), ct.getRoomcount());
				}
				et.setCtMap(ctMap);
			}
			t.setEmtMap(emtmap);
		}
		return li;
	}

	private void setRoomprice(Task t) {
		List<HotelRoom> list = hotelRoomService.findHotelRoomByHotelId(t.getHotelid());
		String roomPrice = "";
		String roomEmPrice = "";
		String roomCount = "";
		for(HotelRoom r: list){
			String sql = "select sum(count) from tb_ct_roomtype "
					+ " where taskid='"+t.getTaskid()+"'"
					+" and roomtypeid=" + r.getId();
			List li = entityManage.findBySql(sql);
			float todaycount = 0;
			if(li.size() != 0 && li.get(0) != null){
				todaycount= Float.parseFloat(li.get(0).toString());//今日房量
			}
			roomPrice += r.getName()+":"+r.getHotelprice()+"\r\n";
			roomEmPrice +=  r.getName()+":"+r.getEmprice()+"\r\n";
			roomCount +=  r.getName()+":"+todaycount+"\r\n";
		}
		t.setRoomprice(roomPrice);
		t.setRoomEmprice(roomEmPrice);
		t.setRoomCount(roomCount);
	}

	@Override
	public Map<String, Integer> getTaskCount() {
		String todaysql = "SELECT COUNT(id) FROM tb_task WHERE TO_DAYS(date_format(creattime,'%Y-%m-%d')) = TO_DAYS(now())";
		String weeksql = "SELECT COUNT(id) FROM tb_task WHERE YEARWEEK(date_format(creattime,'%Y-%m-%d')) = YEARWEEK(now())";
		String mothsql = "SELECT  COUNT(id) FROM  tb_task WHERE DATE_FORMAT( creattime, '%Y%m' ) = DATE_FORMAT( CURDATE() , '%Y%m' )"; 
		
		List tc = entityManage.findBySql(todaysql);
		List wc = entityManage.findBySql(weeksql);
		List mc = entityManage.findBySql(mothsql);
		int todaycount= Integer.parseInt(tc.size() == 0?"0":tc.get(0).toString());//今日
		int weekcount = Integer.parseInt(wc.size() == 0?"0":wc.get(0).toString());//本周
		int monthcount = Integer.parseInt(mc.size() == 0?"0":mc.get(0).toString());//本月
		Map<String, Integer> data = new HashMap<String, Integer>();
		data.put("todaycount", todaycount);
		data.put("weekcount", weekcount);
		data.put("monthcount", monthcount);
		return data;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<Task> getHotelTaskByPage(Integer hotelId,
			Date startTime, Date endTime, Integer pageNo, Integer areaCode) {
		StringBuffer sbf = new StringBuffer("SELECT new Task(t.taskid, t.showapp, t.starttime, t.hotelid, t.emunitprice, t.usercount, t.endtime, t.state) FROM Task  as t , Hotel as h "
				+ " WHERE t.hotelid=h.id and t.showapp = 1 ");
		sbf.append(" AND t.state in(1,2,4,5) ");
		if(hotelId != null){//未传递则查询所有
			sbf.append(" AND t.hotelid= "+hotelId);
		}
		if(startTime != null){
			sbf.append(" AND t.starttime>= '"+DateUtil.formatYMD(startTime)+"'");
		}
		if(endTime != null){
			sbf.append(" AND t.starttime<= '"+DateUtil.formatYMD(endTime)+"'");
		}
		
		if(areaCode != null && areaCode.intValue()>100000){//区域码至少6位
			String w_areaCode = areaCode.toString();
			int x=0;
			String w_area="";
			if(w_areaCode.endsWith("0000")) {
				//精度 省份
				x=9999;
			}else if(w_areaCode.endsWith("00")) {
				//精度 市
				x=99;
			}else {
				//精度 区
				x=0;
			}
			//要的   - 条件  >=0
			//410610-410000 <= 9999
			//410610-410600 <= 99
			//410610-410610 == 0
			w_area=" and convert(h.area,signed) - "+areaCode +" >=0 ";
			w_area+=" and convert(h.area,signed) - "+areaCode +" <= "+x;
			sbf.append(w_area);
			
		}
		
		sbf.append(" order by t.state, t.creattime  ASC");

		return entityManage.findByHqlForPage(sbf.toString(), pageNo, (short)30);
	}

	@Override
	public JSONArray getRoomCountGroupRoomType(String taskId) {
		String sql = "SELECT roomtypeid,roomname,SUM(count) FROM tb_ct_roomtype WHERE taskid='"+taskId+"' GROUP BY roomtypeid, roomname ";
		List<Object> ctLi = entityManage.findBySql(sql);
		JSONArray array = new JSONArray();
		if(ctLi.size()>0){
			for(int i= 0 ; i<ctLi.size(); i++){
				Object[] ory = (Object[]) ctLi.get(i);
				JSONObject js = new JSONObject();
				if(ory[0] != null){//房型ID
					js.put("id", ory[0].toString());
				}
				if(ory[1] != null){//房型ID
					js.put("name", ory[1].toString());
				}
				if(ory[2] != null){//房型ID
					js.put("count", Float.valueOf(ory[2].toString()));
				}
				array.add(js);
			}
		}
		return array;
	}

	@Override
	public void updateTaskState(String taskId, int state) {
		String sql = "UPDATE tb_task SET state="+state+" WHERE taskid = '"+taskId+"'";
		taskDao.updateBySQL(sql);
	}

	@Override
	public Task findTaskByTaskid(String taskid) {
		return taskDao.findTaskByTaskid(taskid);
	}
		
}
